package com.example.service;

import com.example.dao.CommentMapper;
import com.example.dao.StatisticMapper;
import com.example.model.domain.Comment;
import com.example.model.domain.Statistic;
import com.example.service.ICommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    //根据文章id分页查询评论
    @Autowired
    private StatisticMapper statisticMapper;
    @Override
    public PageInfo<Comment> getComments(Integer aid, int page, int count) {
        PageHelper.startPage(page,count);
        List<Comment> commentList=commentMapper.selectCommentWithPage(aid);
        PageInfo<Comment>commentPageInfo=new PageInfo<>(commentList);
        return commentPageInfo;
    }

    @Override
    @Transactional
    public void pushComment(Comment comment) {
        // 插入新的评论
        commentMapper.pushComment(comment);

        // 获取文章的统计信息
        Statistic statistic = statisticMapper.selectStatisticWithArticleId(comment.getArticleId());
        if (statistic != null) {
            // 更新评论数量
            int updatedCommentsNum = statistic.getCommentsNum() + 1;
            statisticMapper.updateArticleCommentsWithId(comment.getArticleId(), updatedCommentsNum);
        } else {
            // 处理找不到统计信息的情况
            throw new RuntimeException("Statistic not found for article ID: " + comment.getArticleId());
        }
    }
}